<template>
  <div>地图演示</div>
  <div>
    {{ mapError }} - {{ city }} - {{ lnglat }} - {{ acValue }} - {{ lnglat2 }}
    <button @click="showMap">发起地图导航</button>
  </div>
  <div class="ac">
    <div>
      <input type="text" v-model="acValue" ref="txtAc" placeholder="请输入地址" />
    </div>

    <div v-if="acValue.trim().length > 0">
      <div v-for="tip in tips" :key="tip.id">
        <div @click="toTip(tip)" class="tip">{{ tip.name }}</div>
      </div>
    </div>
  </div>
  <div class="map-container" id="amap-container"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'
const mapError = ref({})

const lnglat = ref()
const lnglat2 = ref()
const city = ref('430702')
const map = ref()
const marker = ref()
const ps = ref()

const getLocation = () => {
  //@ts-expect-error @typescript-eslint/no-explicit-any
  const geolocation = new AMap.Geolocation({
    enableHighAccuracy: true, // 是否使用高精度定位，默认：true
    timeout: 10000, // 设置定位超时时间，默认：无穷大
    offset: [10, 20], // 定位按钮的停靠位置的偏移量
    zoomToAccuracy: true, //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
    position: 'RB', //  定位按钮的排放位置,  RB表示右下
  })
  map.value.addControl(geolocation)
  //@ts-expect-error @typescript-eslint/no-explicit-any
  geolocation.getCurrentPosition((s, r) => {
    if (s == 'complete') {
      console.log('定位成功：', r)
      lnglat.value = r.position
      map.value.setCenter(r.position)
      //@ts-expect-error @typescript-eslint/no-explicit-any
      marker.value = new AMap.Marker({
        position: r.position,
      })
      map.value.add(marker.value)
      mapError.value = {}
      // 获取城市信息
      getCity()
    } else {
      console.log('定位错误：', s)
      mapError.value = r
    }
  })
}
const getCity = () => {
  // 逆地理编码
  //@ts-expect-error @typescript-eslint/no-explicit-any
  const geocoder = new AMap.Geocoder({
    city: '430702',
  })
  //@ts-expect-error @typescript-eslint/no-explicit-any
  geocoder.getAddress(lnglat.value, (status, result) => {
    if (status === 'complete') {
      console.log('逆地理编码成功：', result)
      city.value = result.regeocode.addressComponent.adcode
      //@ts-expect-error @typescript-eslint/no-explicit-any
      txtAc.value.oninput = autoComplete
      //@ts-expect-error @typescript-eslint/no-explicit-any
      ps.value = new AMap.PlaceSearch({
        city: city.value,
        map: map.value,
      })
    } else {
      console.log('逆地理编码错误：', status)
    }
  })
}

const loadMap = () => {
  AMapLoader.load({
    key: 'e01499dbab923bc5913783dde252868b', //申请好的 Web 端开发 Key，首次调用 load 时必填
    version: '2.0', //指定要加载的 JS API 的版本，缺省时默认为 1.4.15
    plugins: [
      'AMap.ToolBar',
      'AMap.Scale',
      'AMap.Geolocation',
      'AMap.AutoComplete',
      'AMap.PlaceSearch',
      'AMap.Geocoder',
    ], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['AMap.Scale','...','...']
    AMapUI: {
      //是否加载 AMapUI，缺省不加载
      version: '1.1', //AMapUI 版本
      plugins: ['overlay/SimpleMarker', 'misc/PositionPicker'], //需要加载的 AMapUI ui 插件
    },
    Loca: {
      //是否加载 Loca， 缺省不加载
      version: '2.0', //Loca 版本
    },
  })
    .then((AMap) => {
      map.value = new AMap.Map('amap-container', {
        animateEnable: false,
      }) //"container"为 <div> 容器的 id
      map.value.addControl(new AMap.ToolBar({ position: 'LT' }))
      map.value.addControl(new AMap.Scale()) //添加比例尺组件到地图实例上
      // 获取当前位置
      getLocation()
    })
    .catch((e) => {
      console.error(e) //加载错误提示
    })
}

const txtAc = ref(null)
const acValue = ref('')
const tips = ref([])

const autoComplete = () => {
  tips.value = []
  //@ts-expect-error @typescript-eslint/no-explicit-any
  const ac = new AMap.Autocomplete({
    city: city.value,
  })
  //@ts-expect-error @typescript-eslint/no-explicit-any
  ac.search(txtAc.value.value, (status, result) => {
    if (status === 'complete') {
      console.log('自动提示成功：', result)
      tips.value = result.tips
    } else {
      console.log('自动提示错误：', status)
      tips.value = []
    }
  })
}

//@ts-expect-error @typescript-eslint/no-explicit-any
const toTip = (tip) => {
  map.value.setCenter(tip.location)
  marker.value.setPosition(tip.location)
  lnglat2.value = tip.location
  //@ts-expect-error @typescript-eslint/no-explicit-any
  ps.value.search(tip.name, (status, result) => {
    if (status === 'complete') {
      console.log('搜索成功：', result)
    } else {
      console.log('搜索错误：', status)
    }
  })
}

const showMap = () => {
  const url = `https://uri.amap.com/navigation?from=${lnglat.value}&to=${lnglat2.value}`
  window.open(url)
}

onMounted(() => {
  loadMap()
  console.log('txtAc:', txtAc.value)
})

onUnmounted(() => {
  map.value?.destroy()
})
</script>

<style scoped>
.map-container {
  height: 90vh;
  width: 90vw;
  margin: 5px auto;
}

.ac {
  position: fixed;
  top: 6rem;
  right: 8rem;
  background-color: rgba(0, 0, 0, 0.5);
  padding: 5px;
  border-radius: 5px;
  z-index: 100;
  display: flex;
  flex-direction: column;
  width: 20rem;
  input {
    width: 15rem;
  }
  color: #fff;
  .tip {
    cursor: pointer;
    margin: 5px;
    &:hover {
      color: #00f;
    }
  }
}
</style>
